package backend

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"miaoyuadmin/api/backend"
	"miaoyuadmin/api/backend/response"
	"miaoyuadmin/internal/model"
	"miaoyuadmin/internal/service"
	function "miaoyuadmin/utility"
)

var Login = new(loginCtl)

type loginCtl struct {
}

/*
Login
author:licx
*/
func (c *loginCtl) Login(ctx context.Context, req *backend.LoginReq) (res *backend.LoginRes, err error) {
	userId := gconv.Int(service.Auth().GetIdentity(ctx))
	if userId != 0 {
		response.UniResp(g.RequestFromCtx(ctx), "您已登陆，无需重复登录！", "/main.mhtml")
		return
	}

	response.BuildTpl(g.RequestFromCtx(ctx), "login.html").WriteTpl()
	return
}

// LoginDo  待解决：重复登录，原jwt值仍然有效问题，这个会造成一个账户不断刷token,同时refreshToken刷新时也要注销原token
func (c *loginCtl) LoginDo(ctx context.Context, req *backend.LoginDoReq) (res *backend.LoginDoRes, err error) {
	commonJson := response.CommonResp(g.RequestFromCtx(ctx))
	//校验验证码
	capRes := function.CaptchaVerify(req.IdKey, req.Captcha)
	if !capRes {
		commonJson.SetError("验证码输入错误")
		commonJson.WriteJson()
		return
	}
	var in model.UserLoginInput

	if err = g.RequestFromCtx(ctx).Parse(&in); err != nil {
		return
	}
	//校验用户名密码
	checkUser, checkErr := service.Login().CheckUserPassword(ctx, in)

	if checkErr != nil {
		commonJson.SetError("用户名或者密码错误")
		commonJson.WriteJson()
		return
	}
	res = &backend.LoginDoRes{}
	//res.Token, res.Expire = service.Auth().LoginHandler(ctx)
	payloadMap := service.Login().GetPayloadFormat(checkUser)
	res.Token, res.Expire, err = service.Auth().TokenGenerator(payloadMap)
	commonJson.SetSuccessJsonExit("ok", res)
	return
}

func (c *loginCtl) Logout(ctx context.Context, req *backend.LogoutReq) (res *backend.LogoutRes, err error) {
	service.Auth().LogoutHandler(ctx)
	response.UniResp(g.RequestFromCtx(ctx), "退出成功！", "/login.mhtml")
	return
}
